package cn.openea.perpartner.crm.web.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.openea.perpartner.common.core.manager.AsyncManager;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.crm.util.UserContext;
import cn.openea.perpartner.crm.web.entity.CrmMenu;
import cn.openea.perpartner.crm.web.entity.vo.LoginBody;
import cn.openea.perpartner.crm.web.service.ICrmMenuService;
import cn.openea.perpartner.crm.web.service.ICrmUserService;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Weird077
 * @description TODO
 * @date 2022-12-26 19:13
 */
@Slf4j
@ApiModel("登录")
@RestController
@RequestMapping("/crm")
public class CrmLoginController {
    @Value("${sso.url}")
    private String ssoUrl;
    @Autowired
    private ICrmMenuService menuService;
    @Autowired
    private ICrmUserService userService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public String login(@RequestBody LoginBody loginBody) {
        String loginUrl = ssoUrl + "/app/login";
        Map<String, Object> formMap = new HashMap<>(16);
        formMap.put("userId", loginBody.getUsername());
        formMap.put("password", loginBody.getPassword());
        HttpResponse resp = HttpRequest.post(loginUrl)
                .form(formMap)
                .execute();
        AsyncManager.me().execute(userService.asyncUser(loginBody.getUsername()));
        return resp.body();
    }

    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        return null;
    }

    @GetMapping("/getRouters")
    public AjaxResult getRouters() {
        String userId = UserContext.getUserId();
        List<CrmMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

}
